import axios from 'axios';
import { getToken } from '~/composables/auth'
import { toast } from '~/composables/util'
import store from "./store";

const service = axios.create({
    baseURL: '/api',
    // timeout: 1000,
    // headers: {
    //     'X-Custom-Header': 'foobar'
    // }
});
// 添加请求拦截器
service.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    const token = getToken()
    const token_type = "Bearer"
    if (token) {
        // config.headers.authorization  = token
        config.headers.Authorization = token_type + ' ' + token
    }

    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
service.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return Promise.resolve(response.data)
}, function (error) {
    // 对响应错误做点什么
    let data = error.response.data
    if (data['detail'] == "此令牌对任何类型的令牌无效") {
        store.dispatch("logout").finally(() => location.reload())
    }
    else {
        let offset = 0
        if (typeof data == "string") {
            // toast(data || "请求失败！", 'error', offset)
        }
        else {
            for (var obj in data) {
                let msg = ''
                for (var num in data[obj]) {
                    msg += data[obj][num]
                }

                toast(msg || "请求失败！", 'error', offset)
                offset += 100
            }
        }
    }
    return Promise.reject(error);
});



export default service